package com.zhitan.ems.app.stat.config.util;

import java.math.BigDecimal;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.zhitan.ems.app.stat.config.entity.ElectricityTypeSettingItemEntity;
import com.zhitan.ems.app.stat.config.vo.ElectricityMoneyVO;
import com.zhitan.ems.app.stat.entity.StatisticsHourlyEntity;

/**
 * 电费计算工具类
 * 
 * @author zhitan
 * @date 2025-09-29
 */
public class ElectricityCalculationUtil {
	
	public static void main(String[] args) {
		String time="20:30";
		String startTime="20:10";
		String endTime="20:30";
		System.out.println(isTimeInRange(time, startTime, endTime));
	}

    /**
     * 判断指定时间是否在时间范围内
     * 
     * @param time 要检查的时间 (HH:mm格式)
     * @param startTime 开始时间 (HH:mm格式)
     * @param endTime 结束时间 (HH:mm格式)
     * @return 是否在范围内
     */
    public static boolean isTimeInRange(String time, String startTime, String endTime) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
        LocalTime checkTime = LocalTime.parse(time, formatter);
        LocalTime start = LocalTime.parse(startTime, formatter);
        LocalTime end = LocalTime.parse(endTime, formatter);
        // 处理跨天的情况（如22:00-06:00）
        if (start.isAfter(end)) {
            return !checkTime.isAfter(end) || !checkTime.isBefore(start);
        } else {
            return !checkTime.isBefore(start) && !checkTime.isAfter(end);
        }
    }
    
    /**
     * 计算指定小时的电费
     * 
     * @param hour 小时 (0-23)
     * @param consumption 该小时的用电量 (kWh)
     * @param setting 电价设置项
     * @return 该小时的电费
     */
    public static BigDecimal calculateHourlyElectricityCost(int hour, BigDecimal consumption, ElectricityTypeSettingItemEntity setting) {
        if (hour < 0 || hour > 23) {
            throw new IllegalArgumentException("小时必须在0-23之间");
        }
        
        // 将小时转换为HH:mm格式，用于比较
        String hourStr = String.format("%02d:00", hour);
        
        // 检查当前小时是否在时间段内
        if (isTimeInRange(hourStr, setting.getStartTime(), setting.getEndTime())) {
            // 如果在时间段内，则使用对应的电价计算
            return consumption.multiply(setting.getPrice());
        }
        
        // 如果不在时间段内，返回零费用
        return BigDecimal.ZERO;
    }
    /**
     * 计算指定小时的电费
     */
    public static ElectricityMoneyVO calculateHourElectricityCost(StatisticsHourlyEntity statisticsHourly, List<ElectricityTypeSettingItemEntity> settings) {
    	 ElectricityMoneyVO electricityMoneyVO=new ElectricityMoneyVO();
         // 找到适用于当前小时的配置项
         for (ElectricityTypeSettingItemEntity setting : settings) {
             String hourStr = String.format("%02d:00", statisticsHourly.getHour());
             if (isTimeInRange(hourStr, setting.getStartTime(), setting.getEndTime())) {
                 // 计算该小时的电费
                 BigDecimal hourCost = new BigDecimal(statisticsHourly.getSumValue()).multiply(setting.getPrice());
                 electricityMoneyVO.setCost(hourCost);
                 electricityMoneyVO.setType(setting.getElectricityType());
                 return electricityMoneyVO;
             }
         }
         return null;
    }
    
    /**
     * 根据锋平谷配置计算24小时电费
     * 
     * @param hourlyConsumption 24小时用电量数组 (kWh)，索引0-23对应0点到23点
     * @param settings 锋平谷配置项列表
     * @return 包含总电费和分类电费的结果
     */
    public static Map<String, Object> calculate24HourElectricityCost(BigDecimal[] hourlyConsumption, List<ElectricityTypeSettingItemEntity> settings) {
        if (hourlyConsumption == null || hourlyConsumption.length != 24) {
            throw new IllegalArgumentException("hourlyConsumption必须是长度为24的数组");
        }
        // 初始化结果
        Map<String, Object> result = new HashMap<>();
        BigDecimal totalCost = BigDecimal.ZERO;
        Map<String, BigDecimal> typeCosts = new HashMap<>();
        Map<String, BigDecimal> typeConsumptions = new HashMap<>();
        
        // 遍历24小时
        for (int hour = 0; hour < 24; hour++) {
            BigDecimal consumption = hourlyConsumption[hour];
            if (consumption == null) {
                consumption = BigDecimal.ZERO;
            }
            
            boolean hourProcessed = false;
            
            // 找到适用于当前小时的配置项
            for (ElectricityTypeSettingItemEntity setting : settings) {
                String type = setting.getElectricityType();
                String hourStr = String.format("%02d:00", hour);
                
                if (isTimeInRange(hourStr, setting.getStartTime(), setting.getEndTime())) {
                    // 计算该小时的电费
                    BigDecimal hourCost = consumption.multiply(setting.getPrice());
                    
                    // 累加到总电费
                    totalCost = totalCost.add(hourCost);
                    
                    // 累加到分类电费
                    typeCosts.put(type, typeCosts.getOrDefault(type, BigDecimal.ZERO).add(hourCost));
                    
                    // 累加到分类用电量
                    typeConsumptions.put(type, typeConsumptions.getOrDefault(type, BigDecimal.ZERO).add(consumption));
                    
                    // 标记该小时已处理
                    hourProcessed = true;
                    
                    // 一个小时只能属于一种类型，找到后就跳出内层循环
                    break;
                }
            }
            
            // 如果该小时没有匹配的配置项，记录为"未分类"
            if (!hourProcessed && consumption.compareTo(BigDecimal.ZERO) > 0) {
                String type = "未分类";
                // 未分类的电费暂定为0
                BigDecimal hourCost = BigDecimal.ZERO;
                
                // 累加到分类用电量
                typeConsumptions.put(type, typeConsumptions.getOrDefault(type, BigDecimal.ZERO).add(consumption));
            }
        }
        
        // 设置结果
        result.put("totalCost", totalCost);
        result.put("typeCosts", typeCosts);
        result.put("typeConsumptions", typeConsumptions);
        
        return result;
    }
    
    /**
     * 根据锋平谷配置和单一电价计算24小时电费
     * 
     * @param hourlyConsumption 24小时用电量数组 (kWh)，索引0-23对应0点到23点
     * @param settings 锋平谷配置项列表
     * @param singlePrice 单一电价（如果不使用锋平谷计费，则使用此电价）
     * @param usePeakValleyPrice 是否使用锋平谷电价，如果为false则使用单一电价
     * @return 包含总电费和分类电费的结果
     */
    public static Map<String, Object> calculate24HourElectricityCost(BigDecimal[] hourlyConsumption, 
            List<ElectricityTypeSettingItemEntity> settings, BigDecimal singlePrice, boolean usePeakValleyPrice) {
        
        if (!usePeakValleyPrice) {
            // 使用单一电价计算
            Map<String, Object> result = new HashMap<>();
            final BigDecimal totalConsumption = calculateTotalConsumption(hourlyConsumption);
            final BigDecimal totalCost = totalConsumption.multiply(singlePrice);
            
            // 创建分类电费和用电量映射
            Map<String, BigDecimal> typeCosts = new HashMap<>();
            typeCosts.put("单一电价", totalCost);
            
            Map<String, BigDecimal> typeConsumptions = new HashMap<>();
            typeConsumptions.put("单一电价", totalConsumption);
            
            result.put("totalCost", totalCost);
            result.put("totalConsumption", totalConsumption);
            result.put("typeCosts", typeCosts);
            result.put("typeConsumptions", typeConsumptions);
            
            return result;
        } else {
            // 使用锋平谷电价计算
            return calculate24HourElectricityCost(hourlyConsumption, settings);
        }
    }
    
    /**
     * 计算指定日期范围内的电费
     * 
     * @param dailyConsumption 每日用电量数组，每个元素是一个包含24小时用电量的数组
     * @param settings 锋平谷配置项列表
     * @return 包含总电费和分类电费的结果
     */
    public static Map<String, Object> calculateDateRangeElectricityCost(BigDecimal[][] dailyConsumption, 
            List<ElectricityTypeSettingItemEntity> settings) {
        
        // 初始化结果
        Map<String, Object> result = new HashMap<>();
        BigDecimal totalCost = BigDecimal.ZERO;
        Map<String, BigDecimal> typeCosts = new HashMap<>();
        Map<String, BigDecimal> typeConsumptions = new HashMap<>();
        
        // 遍历每一天
        for (BigDecimal[] hourlyConsumption : dailyConsumption) {
            // 计算当天的电费
            Map<String, Object> dailyResult = calculate24HourElectricityCost(hourlyConsumption, settings);
            
            // 累加总电费
            totalCost = totalCost.add((BigDecimal) dailyResult.get("totalCost"));
            
            // 累加分类电费
            @SuppressWarnings("unchecked")
            Map<String, BigDecimal> dailyTypeCosts = (Map<String, BigDecimal>) dailyResult.get("typeCosts");
            for (Map.Entry<String, BigDecimal> entry : dailyTypeCosts.entrySet()) {
                String type = entry.getKey();
                BigDecimal cost = entry.getValue();
                typeCosts.put(type, typeCosts.getOrDefault(type, BigDecimal.ZERO).add(cost));
            }
            
            // 累加分类用电量
            @SuppressWarnings("unchecked")
            Map<String, BigDecimal> dailyTypeConsumptions = (Map<String, BigDecimal>) dailyResult.get("typeConsumptions");
            for (Map.Entry<String, BigDecimal> entry : dailyTypeConsumptions.entrySet()) {
                String type = entry.getKey();
                BigDecimal consumption = entry.getValue();
                typeConsumptions.put(type, typeConsumptions.getOrDefault(type, BigDecimal.ZERO).add(consumption));
            }
        }
        
        // 设置结果
        result.put("totalCost", totalCost);
        result.put("typeCosts", typeCosts);
        result.put("typeConsumptions", typeConsumptions);
        
        return result;
    }
    
    /**
     * 计算总用电量
     * 
     * @param hourlyConsumption 24小时用电量数组
     * @return 总用电量
     */
    private static BigDecimal calculateTotalConsumption(BigDecimal[] hourlyConsumption) {
        BigDecimal totalConsumption = BigDecimal.ZERO;
        
        for (BigDecimal consumption : hourlyConsumption) {
            if (consumption != null) {
                totalConsumption = totalConsumption.add(consumption);
            }
        }
        
        return totalConsumption;
    }
//    public static void main(String[] args) {
//                // 准备24小时用电量数据（kWh）
//        BigDecimal[] hourlyConsumption = new BigDecimal[24];
//        for (int i = 0; i < 24; i++) {
//            hourlyConsumption[i] = new BigDecimal("10"); // 假设每小时10度电
//        }
//        // 获取锋平谷配置列表（从数据库或其他地方）
//        List<ElectricityTypeSettingItemEntity> settings = getElectricityTypeSettings();
//        // 计算电费（使用锋平谷电价）
//        Map<String, Object> result = ElectricityCalculationUtil.calculate24HourElectricityCost(hourlyConsumption, settings);
//
//        // 或者使用单一电价计算
//        BigDecimal singlePrice = new BigDecimal("0.8"); // 假设单一电价为0.8元/kWh
//        Map<String, Object> result2 = ElectricityCalculationUtil.calculate24HourElectricityCost(
//            hourlyConsumption, settings, singlePrice, false);
//        // 获取计算结果
//        BigDecimal totalCost = (BigDecimal) result.get("totalCost");
//        Map<String, BigDecimal> typeCosts = (Map<String, BigDecimal>) result.get("typeCosts");
//        Map<String, BigDecimal> typeConsumptions = (Map<String, BigDecimal>) result.get("typeConsumptions");
//
//    }
}